clc;
clear;
close all;

numOfClass = 15;
numOfTrain = 9;
idOfTest = 11;
height = 100;
width = 100;
key = 1;
numM = 3;

sum = 0;
for key = 1:3
    T = zeros(height, width, numOfClass * numOfTrain);
    for i = 1:numOfClass
        for j = 1:numOfTrain
%           T(:,:,(i-1) * numOfTrain + j) = imread(strcat('D:\Faces\ORL',num2str(key),'\s',num2str(i),'\',num2str(j),'.bmp'));
            T(:,:,(i-1) * numOfTrain + j) = imread(strcat('D:\Faces\YALE', num2str(key),'\s',num2str((i-1)*11+j),'.bmp'));
%           T(:,:,(i-1) * numOfTrain + j) = imread(strcat('D:\Faces\JAFFE', num2str(key),'\s',num2str(i),'\',num2str(j),'.bmp'));
        end
    end
    meanFace = mean(T,3);
    N = numOfTrain * numOfClass;
    CovG = zeros(width, width);
    for i = 1:N
        disToMean = T(:,:,i) - meanFace;
        CovG = CovG + disToMean' * disToMean;
    end
    CovG = CovG / N;
    [eigenFace, eigenValue] = svd(CovG);
    projection = zeros(width, numM);
    for k = 1:numM
        projection(:,k) = eigenFace(:,k);
    end
    allprojectionFace = zeros(height, numM, N);
    for i = 1:N
        allprojectionFace(:,:,i) = T(:,:,i) * projection;
    end
    
%     T = zeros(height, width, numOfClass * 2);
    T = zeros(height, width, numOfClass);
%     tj = 1;
    for i = 1:numOfClass
%       T(:,:,i) = imread(strcat('D:\Faces\ORL',num2str(key),'\s',num2str(i),'\',num2str(idOfTest),'.bmp'));
        T(:,:,i) = imread(strcat('D:\Faces\YALE', num2str(key),'\s',num2str((i - 1) * 11 + idOfTest),'.bmp'));
%       T(:,:,tj) = imread(strcat('D:\Faces\JAFFE', num2str(key),'\s',num2str(i),'\',num2str(idOfTest),'.bmp'));
%       T(:,:,tj + 1) = imread(strcat('D:\Faces\JAFFE', num2str(key),'\s',num2str(i),'\',num2str(idOfTest + 1),'.bmp'));
%       tj = tj + 2;
    end
    right = 0;
%     for i = 1:(numOfClass * 2)
    for i = 1:numOfClass
        afterProjection = T(:,:,i) * projection;
        error = zeros(N,1);
        for ti = 1:N
            miss = afterProjection - allprojectionFace(:,:,ti);
            for tj = 1:size(miss,2)
                error(ti,1) = error(ti,1) + norm(miss(:,tj),1);
            end
        end
        [errorS, errorIndex] = sort(error);
        classIndex = floor((errorIndex(1)-1)/numOfTrain)+1;
%        if classIndex == floor((i + 1)/2)
        if classIndex == i
            right = right + 1;
        end
    end
%     accuracy = right / (numOfClass*2)
    accuracy = right / numOfClass
    sum = sum + accuracy;
end
fprintf('%.4f\n', sum/3);

